/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package screentask;

import com.sun.net.httpserver.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Image;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.util.logging.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author Ahmad
 */
public class frmMain extends javax.swing.JFrame {

    HttpServer serv;
    boolean isWorking=false;
    /**
     * Creates new form frmMain
     *
     * @throws java.net.SocketException
     */

    public frmMain() throws SocketException, IOException, URISyntaxException {
        setTitle("Screen Task");
	setSize(620,420);

	setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new BorderLayout());

        Image img = javax.imageio.ImageIO.read(getClass().getResourceAsStream("/images/ScreenTaskBackground.png"));
        setContentPane(new JLabel(new ImageIcon(img)));
	setLayout(new FlowLayout());

        initComponents();

        Network.LoadIps(cbmIP);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        cbmIP = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        spnPortNum = new javax.swing.JSpinner();
        chkScreenShotEvery = new javax.swing.JCheckBox();
        spnEvery = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        txtURL = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        chkMousePointer = new javax.swing.JCheckBox();
        chkPrivate = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        btnStartServer = new javax.swing.JButton();
        chkPreview = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        lblImage = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBounds(new java.awt.Rectangle(0, 0, 620, 448));
        setName("frmMain"); // NOI18N
        setResizable(false);

        jLabel1.setText("IP : ");

        jLabel2.setText("Port : ");

        spnPortNum.setModel(new javax.swing.SpinnerNumberModel(8888, 1, null, 1));

        chkScreenShotEvery.setText("Take Sceenshot Every :");
        chkScreenShotEvery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkScreenShotEveryActionPerformed(evt);
            }
        });

        spnEvery.setModel(new javax.swing.SpinnerNumberModel(500, 1, null, 1));
        spnEvery.setEnabled(false);
        spnEvery.setValue(500);

        jLabel3.setText("Millisecond");

        txtURL.setEditable(false);
        txtURL.setText("The URL will displayed here after starting the server...");

        jLabel4.setText("URL :");

        chkMousePointer.setText("Capture Mouse Pointer");
        chkMousePointer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkMousePointerActionPerformed(evt);
            }
        });

        chkPrivate.setText("Private Task");
        chkPrivate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkPrivateActionPerformed(evt);
            }
        });

        jLabel5.setText("User :");

        txtUser.setText("screen");
        txtUser.setEnabled(false);

        jLabel6.setText("Password :");

        txtPassword.setText("task");
        txtPassword.setEnabled(false);

        btnStartServer.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btnStartServer.setText("Start Server");
        btnStartServer.setName(""); // NOI18N
        btnStartServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartServerActionPerformed(evt);
            }
        });

        chkPreview.setText("Preview");
        chkPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkPreviewActionPerformed(evt);
            }
        });

        txtLog.setEditable(false);
        txtLog.setColumns(20);
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        lblImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgPrev.png"))); // NOI18N
        lblImage.setMaximumSize(new java.awt.Dimension(210, 140));

        jMenu1.setText("Application");

        jMenuItem2.setText("Exit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 423, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(164, 164, 164)
                                .addComponent(btnStartServer, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jLabel4)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(txtURL))
                                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                            .addComponent(jLabel1)
                                            .addGap(12, 12, 12)
                                            .addComponent(cbmIP, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(jLabel2)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(spnPortNum, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(chkPrivate)
                                        .addGap(25, 25, 25)
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(chkMousePointer)
                            .addComponent(chkPreview)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(chkScreenShotEvery)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(22, 22, 22)
                                        .addComponent(spnEvery, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(1, 1, 1)
                                        .addComponent(jLabel3)))
                                .addGap(96, 96, 96)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(57, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chkScreenShotEvery)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(spnEvery, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addComponent(chkMousePointer))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(cbmIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(spnPortNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkPrivate)
                            .addComponent(jLabel5)
                            .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6)
                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnStartServer, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chkPreview))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(49, 49, 49))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void chkPrivateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkPrivateActionPerformed
        // TODO add your handling code here:
        if (txtUser.isEnabled() && txtPassword.isEnabled()) {
            txtUser.setEnabled(false);
            txtPassword.setEnabled(false);
        } else {
            txtUser.setEnabled(true);
            txtPassword.setEnabled(true);
        }
    }//GEN-LAST:event_chkPrivateActionPerformed

    WebServer webServer = new WebServer();
    ScreenThread screenThread;

    private void btnStartServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartServerActionPerformed
        // TODO add your handling code here:

        if (btnStartServer.getName().equals("")) {
            btnStartServer.setName("start");
            btnStartServer.setText("Start Server");
        }

        try {
              int port = (int) spnPortNum.getValue();
              int every = (int)spnEvery.getValue();
              boolean isPrivate = chkPrivate.isSelected();

            if (btnStartServer.getName().equals("start")) {

                Resources.Log(txtLog, "Starting Server, Please Wait...");
                String ipAddress = (String) cbmIP.getSelectedItem();
                ipAddress = ipAddress.split(" # ")[0];

                btnStartServer.setEnabled(false);
                if(isPrivate)
                {
                    webServer.setUsername(txtUser.getText());
                    webServer.setPassword(new String(txtPassword.getPassword()));

                }

                isWorking = webServer.StartServer(txtLog,ipAddress,port,isPrivate);

                if(isWorking){
                    screenThread = new ScreenThread(every, chkMousePointer.isSelected());

                screenThread.start();

                String url = "http://" + ipAddress + ":" + port;
                txtURL.setText(url);

                btnStartServer.setEnabled(true);
                Resources.Log(txtLog, "Server Started Successfuly!");
                Resources.Log(txtLog, "Private Network URL : " + url);
                Resources.Log(txtLog, "Localhost URL : " + "http://localhost:" + port + "/");

                btnStartServer.setName("stop");
                btnStartServer.setText("Stop Server");
                spnPortNum.setEnabled(false);
                chkPrivate.setEnabled(false);
                txtUser.setEnabled(false);
                txtPassword.setEnabled(false);
                }else{
                    btnStartServer.setEnabled(true);
                    Resources.Log(txtLog, "An error while starting the server");
                }

            } else if (btnStartServer.getName().equals("stop")) {
                if(isWorking){
                btnStartServer.setEnabled(false);
                Resources.Log(txtLog, "Stopping Server, Please Wait...");

                webServer.StopServer(screenThread);

                 Resources.Log(txtLog, "Server Stopped.");

                 btnStartServer.setEnabled(true);
                btnStartServer.setName("start");
                btnStartServer.setText("Start Server");
                    spnPortNum.setEnabled(true);
                    chkPrivate.setEnabled(true);
                    if(chkPrivate.isSelected())
                    {
                        txtUser.setEnabled(true);
                        txtPassword.setEnabled(true);
                    }
                }
            }
        } catch (Exception ex) {

            Resources.Log(txtLog, "Error! : " + ex.getMessage());
        }
    }//GEN-LAST:event_btnStartServerActionPerformed

    private void chkPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkPreviewActionPerformed
        // TODO add your handling code here:

        if(isWorking){
         new javax.swing.Timer(500, new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {

             boolean selected = chkPreview.isSelected();
                if(selected){
                 try {
                     ScreenShot.PreviewImage(lblImage);
                 } catch (URISyntaxException ex) {

                 } catch (MalformedURLException ex) {

                 }
                }
             }
         }).start();
        }
    }//GEN-LAST:event_chkPreviewActionPerformed


    private void chkScreenShotEveryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkScreenShotEveryActionPerformed
        // TODO add your handling code here:
        if (spnEvery.isEnabled()) {
            spnEvery.setEnabled(false);
        } else {
            spnEvery.setEnabled(true);
        }
    }//GEN-LAST:event_chkScreenShotEveryActionPerformed

    private void chkMousePointerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkMousePointerActionPerformed
        // TODO add your handling code here:
        if(isWorking)
            screenThread.mousePointer(chkMousePointer.isSelected());
    }//GEN-LAST:event_chkMousePointerActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
    System.exit(0);
}//GEN-LAST:event_jMenuItem2ActionPerformed

JFrame frame = null;
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws SocketException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frmMain f = new frmMain();
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
                } catch (URISyntaxException ex) {
                    Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStartServer;
    private javax.swing.JComboBox<String> cbmIP;
    private javax.swing.JCheckBox chkMousePointer;
    private javax.swing.JCheckBox chkPreview;
    private javax.swing.JCheckBox chkPrivate;
    private javax.swing.JCheckBox chkScreenShotEvery;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblImage;
    private javax.swing.JSpinner spnEvery;
    private javax.swing.JSpinner spnPortNum;
    private javax.swing.JTextArea txtLog;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtURL;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
